import request from "@/util/httpUtils";
export default {
    config:{
        basePath:request.defaults.baseURL,
        url:'/Admin/Api/uploadFile',
        size:30720,
        name:'file',
		fileType:"all"
    },
    Single(config,uploadStart){
        const conf = config ? {...this.config,...config} : {...this.config};
        return new Promise((res,rej)=>{
            const input = document.createElement("input");
            input.type = 'file';
            input.id = 'upload-file';
            input.style.position = 'fixed';
            input.style.left = '-100%';
            input.style.right = '-100%';
            input.onchange = (e)=>{
                const file = e.target.files[0];
                const {  name,size } = file;
				const fileType = name.slice(name.lastIndexOf("."));
				if(conf.fileType!=='all' && conf.fileType.indexOf(fileType) === -1){
					rej('上传文件格式不正确');
					return;
				}
                if (size > conf.size * 1024) {
                    rej('图片大小超过限制,不能上传超过' + conf.size + 'KB的文件');
                    return;
                }
                const formData = new FormData();
                const xhr = new XMLHttpRequest();
                formData.append(conf.name, file);
                xhr.onreadystatechange = () => {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            const data = JSON.parse(xhr.response);
							data.file = {name,size,fileType};
                            res(data);
                        } else {
							const data = JSON.parse(xhr.response);
							data.file = {name,size,fileType};
                            rej(data);
                        }
                        input.remove();
                    }
                };
                xhr.open('POST', conf.basePath + conf.url, true);
                let token = sessionStorage.getItem('token');
                if(token){
                    xhr.setRequestHeader('Authorization', 'Bearer ' + token);
                }
                xhr.send(formData);
                if(uploadStart){
                    uploadStart();
                }
            };
            document.body.appendChild(input);
            input.dispatchEvent(new MouseEvent('click'));
        })
    }
};